<template>
  <div class="bank-list">
    <!-- 空状态 -->
    <div v-if="filteredBanks.length === 0" class="banks-grid">
      <!-- AI生成题库卡片 -->
      <div class="bank-card ai-generator-card" @click="openAIGenerator">
        <div class="card-content">
          <div class="card-icon">
            <i class="fas fa-robot"></i>
          </div>
          <h3>AI智能生成题库</h3>
          <p>使用AI技术快速生成高质量题库内容</p>
          <div class="ai-features">
            <span><i class="fas fa-bolt"></i> 智能生成</span>
            <span><i class="fas fa-cog"></i> 自定义配置</span>
          </div>
        </div>
        <div class="card-footer">
          <span class="difficulty">
            <i class="fas fa-magic"></i> AI生成
          </span>
        </div>
      </div>
    </div>

    <!-- 题库网格 -->
    <div v-if="filteredBanks.length > 0" class="banks-grid">
      <!-- AI生成题库卡片 -->
      <div class="bank-card ai-generator-card" @click="openAIGenerator">
        <div class="card-content">
          <div class="card-icon">
            <i class="fas fa-robot"></i>
          </div>
          <h3>AI智能生成题库</h3>
          <p>使用AI技术快速生成高质量题库内容</p>
          <div class="ai-features">
            <span><i class="fas fa-bolt"></i> 智能生成</span>
            <span><i class="fas fa-cog"></i> 自定义配置</span>
          </div>
        </div>
        <div class="card-footer">
          <span class="difficulty">
            <i class="fas fa-magic"></i> AI生成
          </span>
        </div>
      </div>

      <!-- 现有题库卡片 -->
      <BankCard
        v-for="bank in filteredBanks"
            :key="bank.bankId"
            :bank="bank"
            :userName="getUserInfo.realName"
            :isCreateCard="false"
            @view="viewBankQuestions"
            @delete="confirmDeleteBank"
        />
    </div>

    <!-- 滚动观察目标 -->
    <div class="observer-target"></div>

    <!-- 加载更多指示器 -->
    <div v-if="loading && hasMoreData" class="load-more-indicator">
      <div class="spinner"></div>
      <p>加载更多题库...</p>
    </div>

    <!-- 到底了提示 -->
    <div v-if="!loading && !hasMoreData && filteredBanks.length > 0" class="end-message">
      <p>— 已经到底了 —</p>
    </div>

    <!-- 题目模态框 -->
    <QuestionModal v-if="currentBank" ref="questionModal" :bank="currentBank" @close="currentBank = null"
      @question-added="handleQuestionChanged" @question-deleted="handleQuestionChanged" />

    <!-- AI生成器模态框 -->
    <AIGenerator v-if="showAIGenerator" :bank-id="selectedBankId" @close="closeAIGenerator"
      @accept="handleAcceptQuestion" @complete="handleGenerationComplete" />

    <!-- 创建题库对话框 -->
    <Dialog v-if="showCreateBankDialog" title="创建新题库" @confirm="createNewBank" @cancel="showCreateBankDialog = false">
      <div class="form-group">
        <label>题库名称</label>
        <input type="text" v-model="newBank.name" placeholder="请输入题库名称" class="form-input">
      </div>
      <div class="form-group">
        <label>题库描述</label>
        <textarea v-model="newBank.description" placeholder="请输入题库描述" class="form-textarea" rows="3"></textarea>
      </div>
    </Dialog>

    <!-- 删除确认对话框 -->
    <ConfirmDialog v-if="$store.state.question.dialogs.deleteConfirm.visible"
      :title="$store.state.question.dialogs.deleteConfirm.title"
      :message="$store.state.question.dialogs.deleteConfirm.message"
      :confirmText="$store.state.question.dialogs.deleteConfirm.confirmText"
      :cancelText="$store.state.question.dialogs.deleteConfirm.cancelText" type="danger"
      @confirm="$store.dispatch('question/confirmDelete')" @close="$store.commit('question/HIDE_DELETE_CONFIRM')" />
  </div>
</template>

<script>
// 引入 题库卡片组件
import BankCard from './BankCard.vue'
// 引入 题目模态框组件
import QuestionModal from './QuestionModal.vue'
// 引入 AI生成器模态框组件
import AIGenerator from './GenerateDialog.vue'
// 引入 确认对话框组件
import ConfirmDialog from './ConfirmDialog.vue'
// 引入 分页组件
import SmartPagination from '../SmartPagination.vue'
// 引入 对话框组件
import Dialog from '../Dialog.vue'

// 引入 Vuex 模块
import { mapState, mapGetters, mapActions } from 'vuex'

export default {
  name: 'BankList',
  components: {
    // 题库卡片组件
    BankCard,
    // 题目模态框组件
    QuestionModal,
    // AI生成器模态框组件
    AIGenerator,
    // 确认对话框组件
    ConfirmDialog,
    // 分页组件
    SmartPagination,
    // 对话框组件
    Dialog
  },
  data() {
    return {
      currentBank: null,
      showAIGenerator: false,
      selectedBankId: null,
      showCreateBankDialog: false,
      showDeleteConfirm: false,
      bankToDelete: null,
      newBank: {
        name: '',
        description: ''
      },
      observer: null,
      loadMoreTrigger: false,
      scrollPosition: 0,
      scrollThrottleTimer: null,
    }
  },
  computed: {
    // 映射 Vuex 中的状态和 getters
    ...mapState('question', [
      'searchQuery',
      'pagination',
    ]),
    ...mapGetters('question', [
      'filteredBanks',
      'paginateBanks',
      'banks'
    ]),
    ...mapGetters('user', [
      'getUserInfo'
    ]),
    loading() {
      return this.$store.state.question.loading
    },
    // 计算属性适配分页组件
    currentPage: {
      get() {
        return this.pagination.currentPage
      },
      set(value) {
        this.setPagination({ currentPage: value })
      }
    },
    pageSize: {
      get() {
        return this.pagination.pageSize
      },
      set(value) {
        this.setPagination({ pageSize: value })
      }
    },
    totalItems() {
      return this.pagination.totalItems
    },
    hasMoreData() {
      return this.pagination.hasMoreData
    }
  },
  created() {
    this.fetchInitialBanks();
    // this.$registerWebSocketHandler(this.handleMessage);
  },
  mounted() {
    // 设置滚动监听
    this.setupInfiniteScroll();
  },
  beforeUnmount() {
    // 移除滚动监听
    this.removeScrollListener();
  },
  methods: {
    // 映射 Vuex actions
    ...mapActions('question', [
      'fetchBanks',
      'fetchMoreBanks',
      'setSearchQuery',
      'setPagination',
      'deleteBank'
    ]),

    // 初始加载题库
    fetchInitialBanks() {
      this.setPagination({
        currentPage: 1,
        pageSize: 10,
        hasMoreData: true
      });
      this.fetchBanks();
    },

    // 加载更多题库
    loadMoreBanks() {
      if (this.loading) {
        // console.log('已在加载中，忽略此次触发');
        return;
      }

      if (!this.hasMoreData) {
        // console.log('没有更多数据，忽略此次触发');
        return;
      }

      // 记录当前滚动位置
      this.scrollPosition = window.scrollY || document.documentElement.scrollTop;
      // console.log('记录滚动位置:', this.scrollPosition);

      // console.log('执行加载更多，当前页码:', this.currentPage, '每页数量:', this.pageSize);

      this.setPagination({
        currentPage: this.currentPage + 1,
        pageSize: 10
      });
      this.fetchMoreBanks().then(() => {
        // 数据加载完成后恢复滚动位置
        this.$nextTick(() => {
          setTimeout(() => {
            window.scrollTo({
              top: this.scrollPosition,
              behavior: 'auto'
            });
            // console.log('恢复滚动位置:', this.scrollPosition);
          }, 50);
        });
      });
    },

    // 设置无限滚动
    setupInfiniteScroll() {
      // 使用Intersection Observer API监听滚动
      this.observer = new IntersectionObserver((entries) => {
        const entry = entries[0];
        if (entry && entry.isIntersecting && !this.loading) {
          // console.log('触发加载更多...');
          this.loadMoreBanks();
        }
      }, {
        root: null,
        rootMargin: '300px',
        threshold: 0.1
      });

      // 创建并观察触发元素
      const createObserverTarget = () => {
        // 先清除旧的观察
        if (this.observer) {
          this.observer.disconnect();
        }

        // 尝试获取已有元素
        let observerTarget = document.querySelector('.observer-target');

        // 如果不存在则创建一个
        if (!observerTarget) {
          observerTarget = document.createElement('div');
          observerTarget.className = 'observer-target';
          observerTarget.style.height = '20px';
          observerTarget.style.width = '100%';

          // 添加到文档中
          const container = document.querySelector('.banks-grid');
          if (container) {
            container.parentNode.insertBefore(observerTarget, container.nextSibling);
          }
        }

        // 开始观察
        if (observerTarget) {
          this.observer.observe(observerTarget);
        }
      }

      // 创建观察目标
      this.$nextTick(() => {
        createObserverTarget();
      });

      // 备用方案：添加滚动事件监听（带节流控制）
      window.addEventListener('scroll', this.handleScrollThrottled);
    },

    // 节流处理的滚动事件
    handleScrollThrottled() {
      if (this.scrollThrottleTimer) return;

      this.scrollThrottleTimer = setTimeout(() => {
        this.handleScroll();
        this.scrollThrottleTimer = null;
      }, 200);
    },

    // 滚动事件处理
    handleScroll() {
      if (this.loading || !this.hasMoreData) return;

      const scrollHeight = document.documentElement.scrollHeight;
      const scrollTop = document.documentElement.scrollTop || window.scrollY;
      const clientHeight = document.documentElement.clientHeight;

      // 当滚动到距离底部300px时加载更多
      if (scrollHeight - scrollTop - clientHeight < 300) {
        this.loadMoreBanks();
      }
    },

    // 移除滚动监听
    removeScrollListener() {
      if (this.observer) {
        this.observer.disconnect();
      }
      window.removeEventListener('scroll', this.handleScrollThrottled);
      clearTimeout(this.scrollThrottleTimer);
    },

    // 处理搜索输入
    handleSearch() {
      this.setSearchQuery(this.searchQuery);
      this.fetchInitialBanks(); // 重置并重新加载
    },

    viewBankQuestions(bank) {
      this.currentBank = bank;
      this.$nextTick(() => {
        if (this.$refs.questionModal && this.$refs.questionModal.open) {
          this.$refs.questionModal.open();
        }
      });
    },
    confirmDeleteBank(bank) {
      // ✅ 先显示确认弹窗，而不是直接调用 confirmDelete
      this.$store.dispatch('question/showDeleteConfirm', bank);
    },

    showCreateDialog() {
      this.newBank = { name: '', description: '' };
      this.seleSctedBankId = null;
      this.showCreateBankDialog = true;
    },

    async createNewBank() {
      if (!this.newBank.name.trim()) { this.$message.warning('请输入题库名称'); return; }

      try {
        // 模拟API创建
        await new Promise(resolve => setTimeout(resolve, 800));
        const newBank = {
          bank_id: Date.now(),
          bank_name: this.newBank.name,
          description: this.newBank.description,
          user_id: 1,
          avg_diffculty: "未设置",
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString(),
          creator: "当前用户",
          question_count: 0
        };

        if (this.selectedBankId) {
          // 更新现有题库
          const index = this.questionBanks.findIndex(
            b => b.bank_id === this.selectedBankId
          );
          if (index !== -1) {
            this.questionBanks.splice(index, 1, {
              ...this.questionBanks[index],
              bank_name: newBank.bank_name,
              description: newBank.description,
              updated_at: new Date().toISOString()
            });
          }
        } else {
          // 添加新题库
          this.questionBanks.unshift(newBank);
        }

        this.$message.success(this.selectedBankId ? '题库更新成功' : '题库创建成功'); this.showCreateBankDialog = false;
      } catch (error) {
        this.$message.error(this.selectedBankId ? '更新题库失败' : '创建题库失败');
      }
    },
    openAIGenerator() {
      this.showAIGenerator = true;
    },
    closeAIGenerator() {
      this.showAIGenerator = false;
    },

    handleAcceptQuestion(question) {
      this.$message.success('题目已添加到题库');      
    },

    // 添加生成完成处理方法
    handleGenerationComplete() {
      console.log('AI生成题库完成');
      this.$message.success('题库生成完成！');
      // 重新获取题库列表以显示最新生成的题库
      this.fetchInitialBanks();
    },

    async handleQuestionChanged() {
      await this.fetchBanks();
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/styles/variables.less";

.bank-list {
  flex: 1;
  width: 100%;
  overflow-y: auto;
  scroll-behavior: smooth;

  &::-webkit-scrollbar {
    width: 5px;
    /* 进一步减小宽度 */
  }

  &::-webkit-scrollbar-track {
    background: transparent;
    margin: 4px 0;
    border-radius: 10px;
  }

  &::-webkit-scrollbar-thumb {
    background: linear-gradient(to bottom, rgba(@primary, 0.1), rgba(@secondary, 0.1));
    /* 使用主题渐变色 */
    border-radius: 10px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    /* 添加细微边框 */
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.05);
    /* 内阴影效果 */
    transition: all 0.3s ease;
  }

  &:hover::-webkit-scrollbar-thumb {
    background: linear-gradient(to bottom, rgba(@primary, 0.2), rgba(@secondary, 0.2));
    /* 悬停时渐变更明显 */
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
  }

  &::-webkit-scrollbar-thumb:active {
    background: linear-gradient(to bottom, rgba(@primary, 0.3), rgba(@secondary, 0.3));
    /* 点击时更深色 */
  }

  /* Firefox 滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: rgba(@primary, 0.2) transparent;
}

.banks-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 2.5rem;
  margin-top: 1rem;
}

.bank-card {
  background: white;
  border-radius: @radius-lg;
  overflow: hidden;
  box-shadow: @shadow-md;
  transition: all 0.3s ease;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  height: 100%;

  &:hover {
    transform: translateY(-5px);
    box-shadow: @shadow-lg;
  }

  .card-content {
    padding: 1.5rem;
    flex: 1;
    display: flex;
    flex-direction: column;

    .card-icon {
      width: 48px;
      height: 48px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: @primary-lighter;
      color: @primary;
      border-radius: @radius-md;
      margin-bottom: 1rem;
      font-size: 1.5rem;
      transition: all 0.3s ease;
    }

    h3 {
      margin: 0 0 0.5rem;
      color: @gray-800;
      font-size: 1.1rem;
      font-weight: 600;
      line-height: 1.3;
    }

    p {
      margin: 0;
      color: @gray-500;
      font-size: 0.875rem;
      line-height: 1.5;
      flex-grow: 1;
    }

    .ai-features {
      margin-top: 1rem;
      display: flex;
      flex-wrap: wrap;
      gap: 0.5rem;

      span {
        font-size: 0.75rem;
        padding: 0.25rem 0.5rem;
        background: @gray-100;
        border-radius: @radius-sm;
        color: @gray-600;
        display: flex;
        align-items: center;
        gap: 0.25rem;

        i {
          color: @primary;
        }
      }
    }
  }

  .card-footer {
    padding: 0.75rem 1.5rem;
    background: @gray-100;
    border-top: 1px solid @gray-200;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;
    align-items: center;
    min-height: 40px;
    height: auto;
    gap: 0.75rem;

    .question-count {
      font-size: 0.875rem;
      color: @gray-600;
    }

    .difficulty {
      font-size: 0.75rem;
      padding: 0.25rem 0.5rem;
      border-radius: @radius-sm;
      background-color: @gray-200;
      color: @gray-700;
      display: flex;
      align-items: center;
      gap: 0.25rem;
    }
  }
}

.ai-generator-card {
  border: 2px dashed @primary-light;
  background-color: white;
  background-image: linear-gradient(135deg, rgba(67, 97, 238, 0.05) 0%, rgba(58, 12, 163, 0.05) 100%);
  position: relative;
  overflow: hidden;

  &::after {
    content: 'NEW';
    position: absolute;
    top: 10px;
    right: -30px;
    width: 100px;
    padding: 0.25rem 0;
    background: @warning;
    color: white;
    font-size: 0.75rem;
    font-weight: bold;
    text-align: center;
    transform: rotate(45deg);
  }

  &:hover {
    border-color: @primary;

    .card-icon {
      background: @primary;
      color: white;
      transform: scale(1.1);
    }
  }

  .card-icon {
    background: linear-gradient(135deg, @primary, @secondary);
    color: white;
  }
}

.form-group {
  margin-bottom: 1.25rem;

  label {
    display: block;
    margin-bottom: 0.5rem;
    font-size: 0.875rem;
    font-weight: 500;
    color: @gray-700;
  }

  .form-input,
  .form-textarea {
    width: 100%;
    padding: 0.75rem 1rem;
    border: 1px solid @gray-300;
    border-radius: @radius-md;
    font-size: 0.9375rem;
    transition: @transition;
    background-color: white;

    &:focus {
      outline: none;
      border-color: @primary;
      box-shadow: 0 0 0 3px rgba(@primary, 0.1);
    }
  }

  .form-textarea {
    min-height: 80px;
    resize: vertical;
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

@media (max-width: 1024px) {
  .banks-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }
}

@media (max-width: 768px) {
  .banks-grid {
    grid-template-columns: repeat(auto-fill, minmax(100%, 1fr));
  }
}

@media (max-width: 480px) {
  .banks-grid {
    grid-template-columns: repeat(auto-fill, minmax(100%, 1fr));
  }
}

/* 滚动加载样式 */
.load-more-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 2rem 0;
  gap: 0.75rem;

  .spinner {
    width: 32px;
    height: 32px;
    border: 3px solid rgba(@primary, 0.1);
    border-top-color: @primary;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  p {
    margin: 0;
    color: @gray-600;
    font-size: 0.875rem;
  }
}

.end-message {
  text-align: center;
  padding: 2rem 0;
  color: @gray-500;
  font-size: 0.875rem;
  margin-top: 1rem;

  p {
    position: relative;
    display: inline-block;
    padding: 0 1rem;

    &::before,
    &::after {
      content: '';
      position: absolute;
      top: 50%;
      width: 30px;
      height: 1px;
      background: @gray-300;
    }

    &::before {
      left: -30px;
    }

    &::after {
      right: -30px;
    }
  }
}
</style>